package com.example.tys.baseapplication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.tys.baseapplication.Mvp.Presenter.BasePresenter;
import com.example.tys.baseapplication.callback.PermissionCallBack;
import com.example.tys.baseapplication.fragment.BaseFragment;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

/**
 * Created by tys on 2017/10/1.
 * Activity基类，基本属性处理
 */

public abstract class BaseActivity<P extends BasePresenter> extends BaseActivityRx<P> {
    private ProgressDialog dialog;
    private Fragment currentFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSystemBarTint();

    }

    protected void initSystemBarTint() {
        Window window = getWindow();
        if (isUseTransStatusBar()) {
            // 设置状态栏全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                window.setNavigationBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        } else {
            // 沉浸式状态栏
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.0以上使用原生方法
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(setStatusBarColor());
                window.setNavigationBarColor(setNavigationBarColor());
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintColor(setStatusBarColor());
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    protected int setNavigationBarColor() {
        return Color.BLACK;
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    protected int setStatusBarColor() {
        return getColorPrimary();
    }

    private int getColorPrimary() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        return typedValue.data;
    }

    protected boolean isUseTransStatusBar() {
        return false;
    }

    public void showLoading() {
        if (dialog == null) {
            dialog = new ProgressDialog(this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage("请求网络中...");
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    public void dismissLoading() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void toast(String context) {
        Toast.makeText(this, context, Toast.LENGTH_SHORT).show();
    }

    public void requestPermission(final PermissionCallBack.OnlyGranted callBack, @NonNull String permission) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.requestEach(permission)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            permissionGrant();
                            if (callBack != null) {
                                callBack.granted(permission);
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            permissionsDenied();
                            if (callBack != null && callBack instanceof PermissionCallBack.GrantedADenied) {
                                ((PermissionCallBack.GrantedADenied) callBack).denied(permission);
                            }
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』，提醒用户手动打开权限
                            toast("权限被拒绝，请在设置里面开启相应权限，若无相应权限会影响使用");
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                            startActivity(intent);
                        }
                    }
                });
    }

    public void requestPermission(final PermissionCallBack.OnlyGranted callBack, @NonNull final String... permissions) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            // All requested permissions are granted
                            permissionGrant();
                            if (null != callBack) {
                                callBack.granted(null);

                            }
                        } else {
                            // At least one permission is denied
                            permissionsDenied();
                            if (null != callBack && callBack instanceof PermissionCallBack.GrantedADenied) {
                                ((PermissionCallBack.GrantedADenied) callBack).denied(null);
                            }
                        }
                    }
                });
    }

    protected void permissionsDenied() {
        toast("权限被拒绝，请在设置里面开启相应权限，若无相应权限会影响使用");
        Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
        startActivity(intent);
    }

    protected void permissionGrant() {
        toast("全部同意");
    }




    protected void replaceFragment(@IdRes int containerViewId, Fragment fragment, @Nullable String tag) {
        getSupportFragmentManager().beginTransaction().replace(containerViewId, fragment, tag).commit();
    }

    protected void showFragment(@IdRes int containerViewId, @NonNull Fragment fragment, @Nullable String tag) {
        FragmentTransaction transFragment = getSupportFragmentManager().beginTransaction();
        if (currentFragment != null && currentFragment != fragment) {
            currentFragment.setUserVisibleHint(false);
            transFragment.hide(currentFragment);
        }
        currentFragment = fragment;
        if (fragment.isAdded()) {
            transFragment.show(fragment);
        } else {
            transFragment.add(containerViewId, fragment, tag);
        }
        fragment.setUserVisibleHint(true);
        transFragment.commit();
    }


}
